$(document).ready(function () {

    var wapper = $('.wapper');

    var render = new Render();
    /**
     * 控件按钮事件
     */
    $('#components')
        .on('click', 'button', function () {
            var data = $(this).attr('data');
            if (!!data) {
                data = JSON.parse(data);
                var type = data['type'], div;

                switch (type) {
                    case 1:
                        //1、背景
                        // render.background();
                        break;
                    case 2:
                        //2、手机号输入框
                        div = render.phoneInput(data);
                        break;
                    case 3:
                        //3、验证码输入框
                        div = render.codeInput(data);
                        break;
                    case 4:
                        //4、验证码发送按钮
                        div = render.codeSendBtn(data);
                        break;
                    case 5:
                        //5、提交按钮
                        div = render.submitBtn(data);
                        break;
                    default:
                        console.log("未知的按钮类型");
                        break;
                }


            }
        })
        .on('change', '#file', function () {
            //从文件中选取图片作为背景
            var reader = new FileReader();
            reader.onload = function () {
                var dataURL = reader.result;
                //背景
                render.background(dataURL);
            };
            reader.readAsDataURL(this.files[0]);
        });

    $('#styles').on('change', 'input', function (e) {
        var key = this.id;
        var unit = $(this).next('.unit').text() || '';
        var select = $('.select');

        var wapperWidth = wapper.width();
        var wapperHeight = wapper.height();

        switch (key) {
            case 'text':
                select.text(this.value);
                break;
            case 'color':
            case 'opacity':
                var color = $('#color').val();
                var opacity = $('#opacity').val();
                select.css("backgroundColor", hexToRgba(color, opacity));
                break;
            default:
                var value = this.value;

                if (value == 100) {
                    if (key === 'height') {
                        select.css("top", 0);
                        value = value / 100 * wapperHeight;
                        unit = 'px';
                    } else if (key === 'width') {
                        select.css("left", 0);
                        value = value / 100 * wapperWidth;
                        unit = 'px';
                    }
                }

                select.css(key, value + unit);
                break;

        }
    });

    $('#delete').click(function (e) {
        $('.select').remove();
        hideStylEditor();
    });

    /**
     * 清除背景图片
     */
    $('#clean').click(function () {
        $('#result').find('.wapper').find('img').remove();

        //清除已选择的文件
        $('.file').empty();
        $('.file').html('<input type="file" id="file" accept="image/*">');

    });

    $('.wapper')
        .click(function () {
            $(this).children().removeClass('select');
            hideStylEditor();
        })
        .on('click', 'div', function (e) {
            /**
             * 点击事件
             * 显示样式编辑器
             */
            e.stopPropagation();

            $('.wapper').children().removeClass('select');
            $(this).addClass("select");

            showStylEditor(this);
        });

    $("#dialog").dialog({
        autoOpen: false,
        width: 414 + 30,
        height: 736 + 30,
        modal: true,
        show: {
            effect: "blind",
            duration: 1000
        }
    });

    initPreviewWindow();


    /**
     * 预览
     * 1、取出 wapper中所有的元素
     * 2、遍历所有元素，并取出data数据、样式
     * 3、根据data中的属性生成不同类型的表单元素
     * 4、设置元素样式
     */
    $('#preview').click(function (e) {
        var content = buildContent();
        $('#preview-dailog').html(content);
        // 打开预览窗口
        openPreviewWindow();
    });

    /**
     * todo 保存
     */
    $('#save').click(function (e) {
        var content = buildContent();
        console.log(content);
        if (!content) {
            return;
        }

        $.ajax({
            url:'http://127.0.0.1:8080/create/html',
            type:'post',
            dataType:'json',
            data:{
                html:$(content).html()
            },
            success:function (resp) {
                alert(resp);
            }

        });
    });


    /**
     * 生成预览内容
     * @returns {*}
     */
    var buildContent = function () {
        var elements = getWapperElements();
        if (!elements || elements.length == 0) {
            return;
        }
        var properties = getElementsProperties(elements);
        if (properties.length == 0) {
            return;
        }

        var div = document.createElement('div');
        for (var i in properties) {
            var element = buildElement(properties[i]);
            $(div).append(element);
        }

        console.log(div);
        return div;
    };

    /**
     * 1、取出 wapper中所有的元素
     */
    var getWapperElements = function () {
        return wapper.children();
    };

    /**
     * 2、遍历所有元素，并取出data数据、样式
     */
    var getElementsProperties = function (elements) {
        var properties = [];
        if (!elements && elements.length == 0) {
            return properties;
        }
        for (var i = elements.length - 1; i >= 0; i--) {
            var item = elements[i];
            var obj = {
                id: item.id,
                data: $(item).data(),
                styles: item.style
            };
            properties.push(obj);
        }
        return properties;
    };

    /**
     * 3、根据data生成页面元素
     */
    var buildElement = function (obj) {
        var id = obj.id;
        var data = obj.data;
        var styles = obj.styles;
        var componentType = data.componentType;
        var css = {}, key, value, element;

        switch (componentType) {
            case 'bg':
                //背景
                element = wapper.find('img').clone();
                break;
            case 'input':
                // 输入框
                element = document.createElement('input');
                element.type = 'text';
                element.placeholder = data.text;
                element.name = data.name;
                break;
            case 'btn':
                // 按钮
                element = document.createElement('button');
                element.textContent = data.text;
                element.name = data.name;
                element.type = 'button';
                if (data.submit) {
                    element.type = 'submit';
                }
                break;
        }

        for (var i = 0; i < styles.length; i++) {
            key = styles[i];
            //todo 宽高，定位都要换算成百分比

            value = styles[key];
            if (!!value) {
                css[key] = value;
            }
        }

        $(element).css(css).attr('id', 'preview' + id);

        return element;
    };


    /**
     * 显示样式编辑器并设置属性值
     * @param obj
     */
    function showStylEditor(obj) {
        console.log(obj.style);

        $('#styles').removeAttr('hidden');

        var text = $(obj).text();
        var style = obj.style;

        var wapper = $('#result .wapper');
        var wapperWidth = wapper.width();
        var wapperHeight = wapper.height();

        var width = 100 * parseInt(style.width) / wapperWidth;
        var height = 100 * parseInt(style.height) / wapperHeight;
        var color = rgbaToHex(style.backgroundColor);
        var opacity = getOpacityFromRgba(style.backgroundColor);
        var fontSize = parseInt(style.fontSize);
        var left = parseInt(style.left);
        var top = parseInt(style.top);


        $('#text').val(text);
        $('#height').val(height.toFixed(2));
        $('#width').val(width.toFixed(2));
        $('#color').val(color);
        $('#opacity').val(opacity);
        $('#fontSize').val(fontSize);
        $('#left').val(left);
        $('#top').val(top);

    }

    /**
     * 隐藏样式编辑器
     */
    function hideStylEditor() {
        $('#styles').attr('hidden', 'hidden');
    }

    /**
     * 初始化预览窗口
     */
    function initPreviewWindow() {
        $('#dialog-wapper').modal('hide')
    }

    /**
     * 打开预览窗口
     */
    function openPreviewWindow() {
        $('#dialog-wapper').modal('show')
    }
});


/**
 * 渲染控件
 *
 * @returns {{background: background, phoneInput: phoneInput, codeInput: codeInput, codeSendBtn: codeSendBtn, submitBtn: submitBtn}}
 * @constructor
 */
var Render = function () {
    var result = $('#result');
    var wapper = result.find('.wapper');
    var wapperWidth = wapper.width();
    var wapperHeight = wapper.height();

    /**
     * 背景
     */
    var background = function (dataURL) {
        var image = new Image();
        image.src = dataURL;
        image.width = wapperWidth;
        var data = $('#bg').attr('data');
        $(image).data(JSON.parse(data));
        wapper.append(image);
    };

    var phoneInput = function (data) {
        return createElement(data);
    };
    var codeInput = function (data) {
        return createElement(data);
    };
    var codeSendBtn = function (data) {
        return createElement(data);
    };
    var submitBtn = function (data) {
        return createElement(data);
    };

    /**
     * 构建将要添加的元素
     * @param data
     */
    function createElement(data) {
        var componentType = data['componentType'];
        var name = data['name'];
        var text = data['text'];
        var isSubmit = data['submit'] || false;

        var component = wapper.find('#' + name);
        if (component.length > 0) {
            return;
        }


        var div = $('<div id="' + name + '" name="' + name + '" type="' + (isSubmit ? "submit" : "") + '">' + text + '</div>');
        var lastElement = wapper.get(0).lastElementChild, lastLeft = 0, lastTop = 0;
        if (!!lastElement) {
            lastLeft = lastElement.offsetLeft;
            lastTop = lastElement.offsetTop;
        }

        // 样式
        div.css({
            color: '#fff',
            width: wapperWidth * 0.8 + 'px',
            position: 'absolute',
            height: '50px',
            left: lastLeft + 10 + 'px',
            top: lastTop + 10 + 'px',
            backgroundColor: 'rgba(0, 0, 0,.2)',
            textAlign: 'center',
            fontSize: '22px',
            'z-index': 1
        });

        div.resizable({
            resize: function (event, ui) {
                $(this).trigger('click');
                // todo 缩放优化
                var width = 100 * parseInt(ui.size.width) / wapperWidth;
                var height = 100 * parseInt(ui.size.height) / wapperHeight;
                console.log(ui.size);
                $('#height').val(height.toFixed(2));
                $('#width').val(width.toFixed(2));
            }
        }).draggable({
            distance: 5,
            drag: function (event, ui) {
                $(this).trigger('click');
                var x = ui.position.left;
                var y = ui.position.top;
                ui.position.left = x < 0 ? 0 : x;
                ui.position.top = y < 0 ? 0 : y;
                var divHeight = div.height();
                var divWidth = div.width();

                var divRigth = x + divWidth;
                var divBottom = y + divHeight;

                if (divRigth > wapper.width()) {
                    ui.position.left = wapperWidth - divWidth - 2;
                }
                if (divBottom > wapperHeight) {
                    ui.position.top = wapperHeight - divHeight - 2;
                }
            }
        });
        div.data(data);
        wapper.append(div);

        wapper.find('#' + name).trigger('click');
        return div;
    }

    return {
        background: background,
        phoneInput: phoneInput,
        codeInput: codeInput,
        codeSendBtn: codeSendBtn,
        submitBtn: submitBtn
    }
};
